import 'package:encrypt/encrypt.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SecureStorage {
  static const _key = 'your_32_byte_encryption_key_here!'; // 替换为你的32字节密钥
  static final _iv = IV.fromLength(16);

  static Encrypter _getEncrypter() {
    return Encrypter(AES(Key.fromUtf8(_key)));
  }

  static Future<void> saveCredentials(String username, String password) async {
    final encrypter = _getEncrypter();
    final prefs = await SharedPreferences.getInstance();
    
    await prefs.setString('username', username);
    
    final encrypted = encrypter.encrypt(password, iv: _iv);
    await prefs.setString('password', encrypted.base64);
  }

  static Future<Map<String, String?>> getCredentials() async {
    final prefs = await SharedPreferences.getInstance();
    final username = prefs.getString('username');
    final encryptedPassword = prefs.getString('password');
    
    String? password;
    if (encryptedPassword != null) {
      try {
        final encrypter = _getEncrypter();
        password = encrypter.decrypt64(encryptedPassword, iv: _iv);
      } catch (e) {
        print('解密失败: $e');
      }
    }
    
    return {'username': username, 'password': password};
  }

  static Future<void> clearCredentials() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('username');
    await prefs.remove('password');
  }
}